package org.eoti.math.cf;

import org.eoti.math.Fraction;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;

/*
 * The MIT License
 *
 * Copyright (c) 2009 Malachi de AElfweald <malachid@gmail.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
public class CFLaTex
{
	public static File createPNG(ContinuedFraction cf, int numTerms)
			throws IOException, InterruptedException
	{
		return createPNG( (new File(".")).getAbsoluteFile(), cf, numTerms);
	}

	public static File createPNG(File directory, ContinuedFraction cf, int numTerms)
			throws IOException, InterruptedException
	{
		File file = new File(directory, cf.getClass().getSimpleName()+".png");
		String frac = createLaTex(cf, numTerms);
		ProcessBuilder pb = new ProcessBuilder(
				new String[]{
						"presentex",
						String.format("\"%s\"", frac),
						"-t",
						"-o",
						String.format("\"%s\"", file.getAbsolutePath())
				}
		);

		/**
		 * not available until JDK7
		 */
//		pb.inheritIO();


		Process process = pb.start();
		if(process.waitFor() != 0)
			return null;

		return file;
	}

	public static String createLaTex(ContinuedFraction cf, int numTerms)
	{
		ArrayList<Fraction> fractions = new ArrayList<Fraction>();
		for( Fraction fraction : cf.getValues())
		{
			if(fraction == null) break;
			fractions.add(fraction);
			if(fractions.size() > numTerms) break;
		}

		Collections.reverse(fractions);

		String s = "";
		if(fractions.size() >= numTerms)
			s = " + {\\ddots\\,}";

		Fraction lastFrac = fractions.remove(0);
		s = String.format("{%s%s}", lastFrac.getDenominator(), s);

		for(Fraction fraction : fractions)
			s = String.format("{%s + \\cfrac{%s}%s}", fraction.getDenominator(), fraction.getNumerator(), s);

		return String.format("%s = %s", cf.toString(), s);
	}
}
